@tool
class_name PlayerData
extends CharacterData


## max: 99999999 -> lvl: 49
@export var total_experience := DataItem.create(0, 0, Constant.MAX_INT)
@export var gold := DataItem.create(0, 0, Constant.MAX_INT)
@export var dash_count := DataItem.create(1, 0, 1)
@export var dash_restore_time: float = 3

var base_exp: int = 100
var growth_rate: float = 1.1

# EXP(level) = base_exp * (growth_rate ^ (level-1)) 
# EXP(level) = base_exp + (level-1)^2 * factor

# total = 100 * (1.1^(level-1) - 100) / (1.1-1)

signal level_changed(ov: int, nv: int)



func _ready() -> void:
    super._ready()

    total_experience.value_changed.connect(
        func(ov: float, nv: float) -> void:
            var old_lvl := calc_level_from_total_experience(int(ov))
            var new_lvl := calc_level_from_total_experience(int(nv))

            if old_lvl != new_lvl:
                print("lvl changed")
                level_changed.emit(old_lvl, new_lvl)
    )


## 计算给定的等级升满所需要的最大经验值，只包含从等级n到等级n+1的经验值
func calc_max_experience_from_level(lvl: int) -> int:
    return int(base_exp * (growth_rate ** (lvl - 1)))


## 计算给定的等级升满所需要的经验值之和，包含从等级1到等级n的所有经验值
func calc_total_experience_from_level(lvl: int) -> int:
    return int(base_exp * (1 - growth_rate ** lvl) / (1 - growth_rate))


## 计算给定的经验值能达到的等级
func calc_level_from_total_experience(t_exp: int) -> int:
    return floori(log(1 - t_exp * (1 - growth_rate) / base_exp) / log(growth_rate)) + 1


func get_level() -> int:
    return calc_level_from_total_experience(int(total_experience.value))


func get_current_level_max_experience() -> int:
    return calc_max_experience_from_level(get_level())


# func get_current_level_total_experience() -> int:
#     return base_exp * (1 - growth_rate ** )
